const jwt = require('jsonwebtoken');
const { secretKey } = require('../config');
const AppError = require('../utils/AppError');
var { expressjwt } = require('express-jwt');
const { sendResult } = require('../utils/tools');

// token 校验
// 验证失败会自动走错误中间件
// 默认从 Headers.Authorization 获取Token进行验证，需要加上 Bearer 的token
// req.auth 可以获取token解析出来的信息
exports.verifyToken = function () {
	return expressjwt({ secret: secretKey, algorithms: ['HS256'] }).unless({
		// 需要排除的路径
		path: [
			{ url: '/api/admin/login', mehtods: ['POST'] },
			{ url: '/api/admin/refresh-token', mehtods: ['POST'] },
			{ url: '/res/captcha', methods: ['GET'] },
			{ url: '/api/banner', methods: ['GET'] },
			{ url: '/api/blogtype', methods: ['GET'] },
			{ url: '/api/blog', methods: ['GET'] },
			{ url: /\/api\/blog\/\d/, methods: ['GET'] },
			{ url: '/api/project', methods: ['GET'] },
			{ url: '/api/message', methods: ['GET', 'POST'] },
			{ url: '/api/comment', methods: ['GET', 'POST'] },
			{ url: '/api/about', methods: ['GET'] },
			{ url: '/api/setting', methods: ['GET'] }

			// { url: /.*/, methods: ['GET'] }
		]
	});
};

// 刷新 token
exports.refreshToken = async (req, res, next) => {
	const { refreshToken } = req.body;

	if (!refreshToken) {
		return res.status(401).json({ message: 'Refresh Token is required' });
	}

	// 检查 Refresh Token 是否有效
	// if (!refreshTokens.includes(refreshToken)) {
	// 	return res.status(403).json({ message: 'Invalid Refresh Token' });
	// }

	// 校验 Refresh Token
	jwt.verify(refreshToken, secretKey, { algorithms: ['HS256'] }, (err, userInfo) => {
		if (err) return next(new AppError(err), 403);
		delete userInfo.iat;
		delete userInfo.exp;

		// 重新生成 Access Token（5分钟 天有效期）
		const accessToken = jwt.sign(userInfo, secretKey, { algorithm: 'HS256', expiresIn: 5 * 60 * 1000 });

		// 返回新的 Access Token
		res.json(
			sendResult({
				accessToken: `Bearer ${accessToken}`,
				refreshToken: `${refreshToken}`
			})
		);
	});
};

// 创建 token
exports.createToken = async (userInfo, next) => {
	return new Promise((resolve) => {
		const data = userInfo || { remember: 1 };
		const expiresIn = 5 * 60;

		// jwt 签名 生成 Access Token（5分钟 天有效期）
		const accessToken = jwt.sign(data, secretKey, { algorithm: 'HS256', expiresIn: expiresIn * 1000 });

		// 生成 Refresh Token（remember 天有效期）
		const refreshToken = jwt.sign(data, secretKey, { algorithm: 'HS256', expiresIn: `${data.remember}d` });

		// 存储 Refresh Token
		// refreshTokens.push(refreshToken);

		resolve({
			accessToken: `Bearer ${accessToken}`, // 加上类型方便 expressjwt 校验
			refreshToken: `${refreshToken}`,
			expiresIn
		});
	});
};
